﻿using Microsoft.AspNetCore.Http;
using MiniFox.Infrastructure;
using MiniFox.Utility;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace MiniFox.Web.Middlewares
{
    /// <summary>
    /// 
    /// </summary>
    public abstract class MiddlewareBase : IMiddleware
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="httpContext"></param>
        /// <param name="next"></param>
        /// <returns></returns>
        public async Task InvokeAsync(HttpContext httpContext, RequestDelegate next)
        {
            try
            {
                var context = new MiddlewareContext(httpContext);
                this.BeforeInvoke(context);
                if (!context.Cancel)
                    await next(httpContext);
                this.AfterInvoke(context);
            }
            catch (Exception e)
            {
                await this.InvokeError(httpContext, e);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        abstract protected void BeforeInvoke(MiddlewareContext context);
        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        abstract protected void AfterInvoke(MiddlewareContext context);

        /// <summary>
        /// 
        /// </summary>
        /// <param name="httpContext"></param>
        /// <param name="exception"></param>
        /// <returns></returns>
        protected async virtual Task InvokeError(HttpContext httpContext, Exception exception)
        {
            var request = httpContext.Request;
            var response = httpContext.Response;
            if (request.IsAjaxRequest())
            {
                response.Clear();
                if (exception is Exceptions.SystemException)
                    response.StatusCode = (int)HttpStatusCode.OK;
                else
                    response.StatusCode = (int)HttpStatusCode.BadRequest;

                await response.WriteAsync(new ErrorResponse(exception).ToJsonString());
            }
        }
    }
}
